<template>
  <div class="accountlist-container">
    <div class="table-header">
      <el-row>
        <el-col :md="{span:16}" :sm="{span:20}" :xs="{span:18}" align="right" class="pull-right">
          <el-input class="col-4" placeholder="请输入用户昵称或手机号" v-model="user_name"></el-input>
          <el-button type="primary" class="search" @click="searchData">查询</el-button>
          <el-button @click="createAccount" type="primary">新增</el-button>
          <el-button type="primary" @click="downModule()">下载模板</el-button>
          <el-upload
            class="upload-demo"
            action
            :on-success="handleAvatarSuccess"
            :http-request="uploadFile"
            :before-remove="beforeRemove"
            multiple
            :show-file-list="false"
            :limit="1"
            :on-exceed="handleExceed"
            name="excels"
            accept=".xls"
            ref="uploadFile"
            :file-list="fileList"
          >
            <el-button type="primary">导入账号</el-button>
          </el-upload>
          <el-button type="primary" class="search" @click="onAppliList">申请列表</el-button>
        </el-col>
      </el-row>
    </div>
    <el-table
      :highlight-current-row="true"
      :header-cell-style="{background:'#f5f5f5'}"
      class="account-list-table"
      :data="accountListData.list"
      border
    >
      <el-table-column label="编号" align="center" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{scope.$index+1}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="user_no" label="用户名" align="center" show-overflow-tooltip></el-table-column>
      <el-table-column prop="user_name" label="用户昵称" align="center" show-overflow-tooltip></el-table-column>
      <el-table-column prop="company_name" label="所属公司" align="center" show-overflow-tooltip></el-table-column>
      <el-table-column prop="dept_name" label="部门" align="center" show-overflow-tooltip></el-table-column>
      <el-table-column prop="job_name" label="岗位" align="center" show-overflow-tooltip></el-table-column>
      <el-table-column prop="phone" label="手机号" align="center" show-overflow-tooltip></el-table-column>
      <el-table-column label="岗位证书" align="center" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{scope.row.has_job_cert=='1'?'有':'无'}}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{scope.row.status=='1'?'正常':'禁用'}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="last_login_date" label="最近登录时间" align="center" show-overflow-tooltip></el-table-column>
      <el-table-column label="操作" width="200" align="center" show-overflow-tooltip>
        <template slot-scope="scope">
          <el-button type="text" @click="showQrcode(scope.row)">二维码</el-button>
          <el-button type="text" @click="printData(scope.row)">打印</el-button>
          <el-button @click="editAccountList(scope.row)" type="text">编辑</el-button>
          <el-button type="text" @click="forst(scope.row)">{{scope.row.status=='1'?'冻结':'启用'}}</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @current-change="handlePageChange"
      :current-page="requestParam.page"
      :page-size="requestParam.page_size"
      layout="total,sizes,prev, pager, next, jumper"
      background
      :total="accountListData.total_count"
      align="center"
    ></el-pagination>
    <!-- 二维码弹窗 -->
    <el-dialog
      title="二维码"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :visible.sync="qrcodeVisible"
      @close="clearCode"
      width="40%"
    >
      <div class="qrCode-box" id="my-node">
        <img class="qrcode" :src="qrcodeUrl" alt />
        <div class="content">
          <p>
            姓名：
            <span>{{qrcodeParams.user_name}}</span>
          </p>
          <p>
            岗位：
            <span>{{qrcodeParams.job_name}}</span>
          </p>
          <p>
            手机号：
            <span>{{qrcodeParams.phone}}</span>
          </p>
          <p class="mid-title">技术支持热线：0571-89192531</p>
        </div>
      </div>
      <span slot="footer" class="dialog-footer"></span>
    </el-dialog>
    <!-- 编辑账号弹窗 -->
    <EditAccountDialog
      :dialogVisible.sync="editAccountDialogVisible"
      @refreshData="refreshList"
      :dialogStatus="editAccountStatus"
      :dialogId="editUserId"
      :dialogForm="accountData"
    ></EditAccountDialog>
    <!-- 打印的二维码 -->
    <div class="print-div" v-show="codeShow" ref="print">
      <div id="my-node-code">
        <div id="qrcode-print" ref="qrcode_print"></div>

        <p>
          姓名：
          <span>{{qrcodeParams.user_name}}</span>
        </p>
        <p>
          岗位：
          <span>{{qrcodeParams.job_name}}</span>
        </p>
        <p>
          手机号：
          <span>{{qrcodeParams.phone}}</span>
        </p>
        <p class="mid-title">技术支持热线：0571-89192531</p>
      </div>
    </div>
    <el-dialog
      title="申请列表"
      :visible.sync="appliListDialogVisible"
      width="75%"
      :before-close="appliListHandleClose"
    >
      <AppliListDialog :judgeOpen="judgeOpen" :callBack="callBack"></AppliListDialog>
    </el-dialog>
  </div>
</template>
<script>
import AppliListDialog from "./components/AppliListDialog";
import EditAccountDialog from "./components/EditAccountDialog";
import { accountApi } from "@/services/CompanySetting";
import { organizationApi } from "@/services/CompanySetting";
// import { standardCodeApi } from '@/services/StandardCode'
import QRCode from "qrcodejs2"; // 引入qrcode
import domtoimage from "dom-to-image";
import { setInterval, clearInterval } from "timers";
export default {
  data() {
    return {
      loading: false, //导入文件加载中
      qrcodeUrl: "",
      judgeOpen: 0, //1：打开弹框；0：关闭弹框
      appliListDialogVisible: false,
      user_name: "",
      requestParam: {
        page: 1,
        page_size: 10
      },
      accountListData: {
        list: [],
        total_page: 0,
        total_count: 0
      },
      // 新增/修改账号弹框是否可见
      editAccountDialogVisible: false,
      // 新增或修改账号状态
      editAccountStatus: "edit",
      editUserId: "",
      // 新增或修改账号数据对象
      accountData: {
        user_name: "",
        real_name: "",
        job_id: "",
        phone: ""
      },
      qrcodeVisible: false, // 二维码弹窗
      qrcodeParams: {
        phone: "",
        user_name: "",
        job_name: ""
      },
      forst_status: "",
      forst_id: "",
      fileList: [],
      comp_id: "",
      codeShow: false,
      userInfo: {},
      companyInfo: {}
    };
  },
  components: {
    EditAccountDialog,
    AppliListDialog
  },
  methods: {
    callBack() {
      this.judgeOpen = 0; //1：打开弹框；0：关闭弹框
      this.appliListDialogVisible = false;
    },
    appliListHandleClose(done) {
      //申请列表关闭前触发的事件
      this.callBack();
      done();
    },
    //申请列表
    onAppliList() {
      this.judgeOpen = 1;
      this.appliListDialogVisible = true;
      console.log("申请列表");
    },
    // 分页
    handlePageChange(page) {
      this.requestParam.page = page;
      this.getAccountList();
    },
    // 搜索
    searchData() {
      this.requestParam.page = 1;
      this.getAccountList();
    },
    // 打印
    printData(row) {
      // my-node
      this.codeShow = true;
      this.qrcodeParams.job_name = row.job_name;
      this.qrcodeParams.phone = row.phone;
      this.qrcodeParams.user_name = row.user_name;
      var that = this;
      var timer = null;
      var count = 0.1;
      let qrcode = new QRCode(this.$refs.qrcode_print, {
        width: 180,
        height: 180,
        text: row.user_id, // 二维码地址
        colorDark: "#000",
        colorLight: "#fff"
      });
      timer = setInterval(function() {
        count--;
        that.$print(that.$refs.print);
        if (count <= 0) {
          clearInterval(timer);
          document.getElementById("qrcode-print").innerHTML = "";
          that.codeShow = false;
        }
      }, 100);
      // 使用
      // window.print();
      // window.print()
    },
    // 显示二维码
    showQrcode(row) {
      this.qrcodeParams.job_name = row.job_name;
      this.qrcodeParams.phone = row.phone;
      this.qrcodeParams.user_name = row.user_name;
      this.qrcodeVisible = true;
      var timer = null;
      var count = 0.5;
      this.getUserQRCode(row);
      // timer = setInterval(function () {
      //   count--
      //   if (count <= 0) {
      //     clearInterval(timer)
      //     domtoimage.toPng(document.getElementById('my-node'))
      //       .then(function (dataUrl) {
      //         var link = document.createElement('a')
      //         link.download = row.user_id + '.png'
      //         link.href = dataUrl
      //         link.click()
      //       })
      //   }
      // }, 500)
    },
    getUserQRCode(row) {
      accountApi
        .getUserQRCode({
          data: {
            company_id: row.comp_id,
            type: "user",
            text: row.user_id,
            footer: "单位邀请码：{邀请码},{单位名称}"
          }
        })
        .then(res => {
          let a = document.createElement("a");
          let blob = new Blob([res], { type: "image/png" });
          let url = URL.createObjectURL(blob);
          this.qrcodeUrl = url;
          a.href = url;
          a.download = "人员二维码";
          a.target = "_blank";
          a.click();
        });
    },
    // 清除二维码
    clearCode() {
      document.getElementById("qrcode").innerHTML = "";
    },
    // 下载模板
    downModule() {
      var alink = document.createElement("a");
      // if (location.hostname === 'localhost') {
      //   alink.href = 'http://dev_console_api.ihibuilding.cn/api/v1/user/user/get_user_download?file_name=systemUser.xls'
      // } else if (location.hostname === 'dev_platform.ihibuilding.cn') {
      //   alink.href = 'http://dev_console_api.ihibuilding.cn/api/v1/user/user/get_user_download?file_name=systemUser.xls'
      // } else {

      // }
      alink.href =
        "//release-console-new.oss-cn-hangzhou.aliyuncs.com/hibuilding/systemUser.xls";
      alink.download = ""; // 图片名
      alink.click();
    },
    // 上传文件
    uploadFile(params) {
      const loading = this.$loading({
        lock: true,
        text: "上传中",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      var formData = new FormData();
      formData.append("comp_id", this.userInfo.comp_id);
      formData.append("excels", params.file);
      accountApi
        .uploadAccount({
          data: formData
        })
        .then(
          res => {
            if (res.code === 0) {
              this.$message.success("上传成功");
              loading.close();
              this.searchData();
            } else {
              loading.close();
            }
            this.$refs.uploadFile.clearFiles();
          },
          err => {
            loading.close();
            this.$message.error();
            ("上传失败");
            this.$refs.uploadFile.clearFiles();
          }
        );
    },
    // 上传文件限制
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 1 个文件，本次选择了 ${
          files.length
        } 个文件，共选择了 ${files.length + fileList.length} 个文件`
      );
    },
    // 移除上传的文件
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    // excel数据导入，上传成功的钩子
    handleAvatarSuccess(res, excels) {},
    // 添加功能
    createAccount() {
      this.editAccountStatus = "add";
      this.accountData = {};
      this.editAccountDialogVisible = true;
    },
    // 编辑功能
    editAccountList(row) {
      let data = {};
      data.user_name = row.user_no;
      data.real_name = row.user_name;
      data.phone = row.phone;
      data.job_id = row.job_name;
      data.user_id = row.user_id;
      data.job_cert = row.job_cert;
      this.editUserId = row.user_id;
      console.log("row===", row);
      this.accountData = data;
      this.editAccountStatus = "edit";
      this.editAccountDialogVisible = true;
    },
    // 打开冻结与启用弹窗
    forst(row) {
      var name = "";
      if (row.status == "1") {
        name = "冻结";
      } else {
        name = "启用";
      }
      this.forst_id = row.user_id;
      this.forst_status = row.status;
      this.$confirm("是否" + name + '"' + row.user_name + '"帐号 ? ', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        left: true
      })
        .then(() => {
          this.sureForst();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消操作"
          });
        });
    },
    frostAccount() {
      accountApi
        .frostAccount({
          data: {
            type: this.forst_status,
            user_id: this.forst_id
          }
        })
        .then(res => {
          if (res.code === 0) {
            this.$message.success("操作成功");
            this.getAccountList();
          }
        });
    },
    // 确认冻结账号
    sureForst() {
      if (this.forst_status === "1") {
        this.forst_status = "2";
        this.frostAccount();
      } else {
        this.forst_status = "1";
        this.frostAccount();
      }
    },
    refreshList() {
      this.getAccountList();
    },
    // 获取列表
    getAccountList() {
      accountApi
        .getDeptUserList({
          data: {
            company_id: this.userInfo.comp_id,
            dept_no: this.userInfo.dept_no,
            type: 1,
            all_status: "1",
            is_page: 1,
            page: this.requestParam.page,
            page_size: this.requestParam.page_size,
            user_name: this.user_name
          }
        })
        .then(res => {
          this.accountListData.list = res.data.list;
          this.accountListData.total_count = res.data.total_count;
        });
    },
    // 获取组织树数据
    getOrgTree() {
      organizationApi.getOrgTree({}).then(
        res => {
          console.log(res, "get org tree");
          let data = res.data;
          console.log(data, "handle data");
          this.$store.dispatch("setOrgainzationTree", data);
          window.localStorage.setItem(
            "platformOrganizationTree",
            JSON.stringify(data)
          );
        },
        err => {
          console.log(err);
        }
      );
    }
    // 获取标准码
    // getcode () {
    //   standardCodeApi.getStandardCodeData({
    //     data: {
    //       code_type: 'user_status'
    //     }
    //   }).then(res => {
    //     console.log('codeVal', res)
    //   })
    // }
  },
  created() {
    let storage = window.localStorage.getItem("userInfo") || "{}";
    this.userInfo = JSON.parse(storage);
    let companyStorage = window.localStorage.getItem("companyInfo") || "{}";
    this.companyInfo = JSON.parse(companyStorage);
    this.getOrgTree(); // 获取组织树数据
    this.getAccountList();
    // this.getcode()
  }
};
</script>
<style scoped lang='scss'>
@media print {
  .a {
    display: none;
  }
}
.qrcode {
  width: 300px;
  height: 300px;
}
.accountlist-container {
  padding: 15px;
  /deep/ .qrCode-box {
    display: flex;
    .content {
      flex: 1;

      p {
        width: 180px;
        margin: 0 auto;
        text-align: center;
        font-weight: bold;
        line-height: 36px;
      }
    }
  }
  .mid-title {
    font-size: 12px;
  }
  .forst_account {
    color: #1890ff;
    font-weight: bold;
  }
  /deep/ #qrcode img {
    margin: 0 auto !important;
  }
  .table-header {
    width: 100%;
    height: 74px;
    background-color: #fff;
    margin-bottom: 20px;
    border-bottom: 1px solid #eee;
    .upload-demo {
      width: 98px;
      display: inline-block;
      margin-left: 10px;
    }
    .search {
      margin-left: 10px;
    }
  }
  .account-list-table {
    margin-bottom: 20px;
  }
  .edit-account-form {
    .el-select {
      width: 100%;
    }
  }
}
.print-div {
  margin-top: 50px;
}
</style>